package com.hp.team.bookstore.service.profile;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hp.team.bookstore.dbaccess.dao.profile.CreditCardHibernateDAO;
import com.hp.team.bookstore.dbaccess.dao.profile.CustomerHibernateDAO;
import com.hp.team.bookstore.dbaccess.dao.profile.UserHibernateDAO;
import com.hp.team.bookstore.model.profile.CreditCard;
import com.hp.team.bookstore.model.profile.Customer;
import com.hp.team.bookstore.model.profile.User;

@Service
public class ProfileService {

	@Autowired
	private UserHibernateDAO userDAO;

	@Autowired
	private CustomerHibernateDAO customerDAO;

	@Autowired
	private CreditCardHibernateDAO creditCardDAO;

	@Transactional
	public List<User> getAllUsers() {
		return userDAO.findAll();
	}

	@Transactional
	public List<Customer> getAllCustomers() {
		return customerDAO.findAll();
	}

	@Transactional
	public Customer getCustomer(long id) {
		return customerDAO.findById(id, false);
	}

	@Transactional
	public List<Customer> getCustomerByMail(String email) {
		List<Customer> allCustomers = customerDAO.findAll();
		List<Customer> filteredCustomersByMail = new ArrayList<Customer>();
		for (Customer c : allCustomers) {
			if (c.getEmail().equalsIgnoreCase(email))
				filteredCustomersByMail.add(c);
		}
		return filteredCustomersByMail;
	}

	@Transactional
	public CreditCard getCreditCard(long id) {
		return creditCardDAO.findById(id, false);
	}

	@Transactional
	public List<CreditCard> getCreditCardByCustomerID(long id) {
		List<CreditCard> allCreditCards = creditCardDAO.findAll();
		List<CreditCard> customerCreditCards = new ArrayList<CreditCard>();
		for (CreditCard card : allCreditCards) {
			if (card.getCustomer().getId() == id) {
				customerCreditCards.add(card);
			}
		}
		return customerCreditCards;
	}
	
	@Transactional
	public long addNewCustomer(Customer c) {
		Customer temp = customerDAO.makePersistent(c);
		return temp.getId();
	}

}
